//
//  MqForumChoiceDetailViewController.m
//  Meiqi
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 KFC. All rights reserved.
//

#import "MqForumChoiceDetailViewController.h"
#import "MqForumDetailSettingsViewController.h"
#import "MqForumDetailModel.h"
#import "MqForumDetailTableViewCell.h"
#import <UMSocialWechatHandler.h>
@interface MqForumChoiceDetailViewController ()
<UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate, UITextFieldDelegate, UMSocialUIDelegate>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) NSInteger startPage;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) MBProgressHUD *progressHUD;

@property (nonatomic, strong) UIView *editView;
@end

@implementation MqForumChoiceDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //  初始化
    _startPage = 1;
    
    //  初始化数据源数组
    _dataArray = [NSMutableArray array];
    
    //  设置导航栏显示
    self.navigationController.navigationBar.hidden = NO;
    
    //  隐藏tabBar
    self.tabBarController.tabBar.hidden = YES;
    
    //  白色背景色
    self.view.backgroundColor = [UIColor whiteColor];
    
    //  导航栏button:设置, 分享, 收藏
//    UIBarButtonItem *setBarItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_menu@2x"] style:(UIBarButtonItemStylePlain) target:self action:@selector(settings:)];
    
    UIBarButtonItem *shareBarItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"info-share@2x"] style:(UIBarButtonItemStylePlain) target:self action:@selector(share:)];
    [shareBarItem setBackButtonBackgroundImage:[UIImage imageNamed:@"btn_share_highlighted@2x"] forState:(UIControlStateHighlighted) barMetrics:UIBarMetricsDefault];
    
    UIBarButtonItem *collectionBarItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_collection_new@2x"] style:(UIBarButtonItemStylePlain) target:self action:@selector(collection:)];
    [collectionBarItem setBackButtonBackgroundImage:[UIImage imageNamed:@"btn_collection_selected@2x"] forState:(UIControlStateSelected) barMetrics:UIBarMetricsDefault];
    
    //  把button添加进导航栏的右边
    self.navigationItem.rightBarButtonItems = @[shareBarItem];
    
    
    [self dataProcess];
    [self addTableView];
    self.tableView.hidden = YES;
    [self setupProgressHud];
    
    //  添加上拉下拉刷新
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        _startPage = 1;
        [self dataProcess];
        
    }];
    
    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
       
        _startPage = _startPage + 1;
        [self dataProcess];
        
    }];
    
}

//  设置菊花
- (void)setupProgressHud{
    
    _progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
    _progressHUD.frame = self.view.bounds;
    _progressHUD.mode = MBProgressHUDModeIndeterminate;
    _progressHUD.minSize = CGSizeMake(80, 80);
    [self.view addSubview:_progressHUD];
    [_progressHUD show:YES];
    
}


//  设置按钮:进入设置界面
- (void)settings:(UIBarButtonItem *)barButton{
    
    MqForumDetailSettingsViewController *settingsVC = [[MqForumDetailSettingsViewController alloc] init];
    
    [self.navigationController pushViewController:settingsVC animated:YES];
}

// 分享
- (void)share:(UIBarButtonItem *)barItem{
    
    [UMSocialWechatHandler setWXAppId:@"wx764df7e9fd624000" appSecret:@"a1c4625fd9b271f1b8bb30c761c70203" url:[NSString stringWithFormat:@"http://bbs.biketo.com/thread-%@-1-1.html", _forumModel.tid]];
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                    appKey:@"569d972fe0f55a319300057c"
                                      shareText:[NSString stringWithFormat:@"%@ http://bbs.biketo.com/thread-%@-1-1.html",_forumModel.msginfos, _forumModel.tid]
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession, UMShareToWechatFavorite, UMShareToWechatTimeline, UMShareToQQ,nil]
                                       delegate:self];
    
    
    
    //  设置分享内容和回调对象
//    [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina].snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
    
       //注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
//     [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToSina] content:@"分享内嵌文字" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
//     if (response.responseCode == UMSResponseCodeSuccess) {
//     NSLog(@"分享成功！");
//     }
//     }];
    
}

//  实现回调方法（可选）:

//-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
//{
//    //根据`responseCode`得到发送结果,如果分享成功
//    if(response.responseCode == UMSResponseCodeSuccess)
//    {
//        //得到分享到的微博平台名
//        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
//    }
     


//  收藏
- (void)collection:(UIBarButtonItem *)barItem{
    
    
    
    
}


- (void)addTableView{

    self.automaticallyAdjustsScrollViewInsets = NO;
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:(UITableViewStyleGrouped)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    //  tableView表头设置
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
    
    UILabel *subjectLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, kScreenWidth - 40, 40)];
    subjectLabel.text = _forumModel.subject;
    subjectLabel.textAlignment = NSTextAlignmentCenter;
    [view addSubview:subjectLabel];

    _tableView.tableHeaderView = view;
    
    
    // 注册cell
    [_tableView registerClass:[MqForumDetailTableViewCell class] forCellReuseIdentifier:@"MqForumDetailTableViewCell"];
    
    //  编辑视图
   _editView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 50, kScreenWidth, 50)];
    _editView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_editView];
    
    //  编辑框
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, kScreenWidth - 80, 40)];
    textField.backgroundColor = [UIColor lightGrayColor];
    textField.placeholder = @"评论";
    textField.delegate = self;
    
    textField.layer.cornerRadius = 10;
    
    [_editView addSubview:textField];
    
    UIButton *commentButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    commentButton.frame = CGRectMake(textField.right + 10, 5, 50, 40);
    commentButton.backgroundColor = [UIColor redColor];
    commentButton.layer.cornerRadius = 15;
    [commentButton setTitle:@"评论" forState:(UIControlStateNormal)];
    [_editView addSubview:commentButton];
    
}

//  数据处理
- (void)dataProcess{
    
    NSString *path = [NSString stringWithFormat:@"http://bbs.biketo.com/api/mobile/index.php?module=viewthread&page=%ld&ppp=10&tid=%@&version=4", (long)_startPage, _forumModel.tid];
    
    
    [PKRequestManager requestWithUrlString:path parDic:nil Method:GET finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        if (dic != nil) {
                
                [_dataArray removeAllObjects];
        }
        
        NSArray *listArray = dic[@"Variables"][@"postlist"];
        
        for (NSDictionary *oneDic in listArray) {
            
            MqForumDetailModel *model = [[MqForumDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            
            model.isRefreshed = NO;
            [_dataArray addObject:model];
            
        }
        
        MqForumDetailModel *detailModel = _dataArray[0];
        
        if (detailModel.message != nil) {
            //  刷新tableView
            [_tableView reloadData];
        }
        
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        
    } error:^(NSError *error) {
        
    } path:nil];

}

#pragma mark --- scrollView代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    _editView.hidden = YES;
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    _editView.hidden = NO;
    
}

#pragma mark --- tableView代理方法
//  分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
    
}

//  返回行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

//    return
    MqForumDetailModel *detailModel = _dataArray[indexPath.row];

    return  detailModel.cellHeight;
    
}

//  返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MqForumDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MqForumDetailTableViewCell" forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    MqForumDetailModel *detailModel = _dataArray[indexPath.row];

    cell.detailModel = detailModel;
    
    NSString *xmlString = detailModel.message;
    
    xmlString = [xmlString stringByReplacingOccurrencesOfString:@"<img src=\"http\://bbs.biketo.com/data/attachment/forum/" withString:@"<img height=\"400\" width= \"370\" src=\"http\://bbs.biketo.com/data/attachment/forum/"];
   
    cell.messageWebV.frame = CGRectMake(20, 60, kScreenWidth - 40, detailModel.cellHeight - 60);
    cell.messageWebV.tag = indexPath.row + 100;
    [cell.messageWebV loadHTMLString:xmlString baseURL:nil];
    cell.messageWebV.delegate = self;
    
    return cell;
    
}

//  隐藏菊花 ,显示tableView
- (void)hideProgress{
    
    [_progressHUD hide:YES];
    _tableView.hidden = NO;
    
}

//  webView加载完成时执行的方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    NSInteger index = webView.tag - 100;
    
    MqForumDetailModel *detailModel = _dataArray[index];
    
    detailModel.cellHeight = webView.scrollView.contentSize.height + 60;
    
    //  刷新cell的方法只执行一次
    if (detailModel.isRefreshed == NO) {
        
        //  设置已经刷新过
        detailModel.isRefreshed = YES;
        
        //  刷新加载完成的cell
        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:(UITableViewRowAnimationNone)];

    }
    //  加载完最后一个Cell时隐藏菊花 并显示tableView
    if (index == _dataArray.count - 1) {
        
        //  延迟1秒出现
        [self performSelector:@selector(hideProgress) withObject:self afterDelay:1];
    }
}


- (void)viewWillDisappear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
